package com.pajk.user.service.common.tair;

import java.util.ArrayList;
import java.util.List;

import com.taobao.tair.TairManager;
import com.taobao.tair.impl.DefaultTairManager;
import org.springframework.beans.factory.FactoryBean;

public class TairManagerFactoryBean implements FactoryBean<TairManager> {

	private DefaultTairManager tairManager;
	private String configServer;
	private String groupName;

    private int timeout;

    @Override
    public TairManager getObject() throws Exception {
        if((configServer == null) || (groupName == null)){
            // fail fast
            throw new Exception("Need configServer or/and groupName be configured properly!");
        }

        if(tairManager == null){
            List<String> confServers = new ArrayList<String>();
            confServers.add(configServer);
            // 创建客户端实例
            tairManager = new DefaultTairManager();
            tairManager.setConfigServerList(confServers);
            // 设置组名
            tairManager.setGroupName(groupName);
            tairManager.setTimeout(timeout);
            // 初始化客户端
            tairManager.init();
        }

        return tairManager;
    }

    public void destroy(){
        if (tairManager != null){
            tairManager.close();
        }
    }

    @Override
    public Class<?> getObjectType() {
        return TairManager.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    public void setConfigServer(String configServer) {
        this.configServer = configServer;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
}
